import axios from 'axios';
import {Message} from 'element-ui'
import router from '../router'

axios.interceptors.request.use(
    config => {
        // 有令牌信息则带上
        if (localStorage.getItem('tokenStr')) {
            config.headers['Authorization'] = localStorage.getItem('tokenStr')
        }
        return config;
    }, error => {
        console.log(error.message);
    })
// 响应拦截器
axios.interceptors.response.use(
    success => {
        // “正常”业务逻辑（code 业务状态码)
        // 服务器正常工作 2xx
        if (success.status && success.status == 200) {
            let code = success.data.code;
            switch (code) {
                case "500":
                case "401":
                case "403":
                    // 登录行为失败
                    Message.error({message: success.data.message});
                    return;
            }
            if (success.data.message) {
                Message.success({message: success.data.message})
            }
        }
        return success.data;
    },
    error => {
        // HTTP状态码 !2xx
        // let code = error.response.code;
        // let code = error.response.data.code;
        console.log(error)
        let status = error.response.status;
        if (status == 504 || status == 404) {
            Message.error({message: '服务器挂了o(╯□╰)o'})
        } else if (status == 403) {
            Message.error({message: '权限不足，请联系管理员！'})
        } else if (status == 401) {
            Message.error({message: '尚未登录，请登录'})
            //登录路由
            router.replace('/');
        } else {
            if (error.response.data.message) {
                Message.error({message: error.response.data.message})
            } else {
                Message.error({message: '未知错误'})

            }
        }
        return;

    }
)

let base = '';
//urlencode格式的get请求
export function getRequest(url, params='') {
    return axios({
        method: 'get',
        url: `${base}${url}`,
        params //urlencoded
    })
}

// 传送json格式的Post请求
export function postRequest(url, params) {
    return axios({
        method: 'post',
        url: `${base}${url}`,
        data: params
    })
}

// 传送json格式的Put请求
export function putRequest(url, params) {
    return axios({
        method: 'put',
        url: `${base}${url}`,
        data: params
    })
}

// 传送json的delete请求
export function deleteRequest(url, params) {
    return axios({
        method: 'delete',
        url: `${base}${url}`,
        data: params
    })
}

